#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author:liang futing
#@Time :2019/4/9 14:09
import re
from django.template import Library
from django.conf import settings
from collections import OrderedDict
from django.urls import reverse
from django.http import QueryDict
from rbac.service import urls
register=Library()


@register.inclusion_tag('rbac/static_menu.html')
def static_menu(request):
    menu_list=request.session.get(settings.MENU_SESSION_KEY)
    for item in menu_list:
        regex="^%s$"%item['url']
        if re.match(regex,request.path_info):
            item['class']='active'
    # print(menu_list)
    # return {'menu_list':request.session.get(settings.MENU_SESSION_KEY)}
    return {'menu_list': menu_list}
    #一级菜单功能保留着吧


@register.inclusion_tag('rbac/multi_menu.html')
def multi_menu(request):
    """

{1: {'title': '客户管理', 'icon': 'fa-connectdevelop',
    'children': [{'title': '客户列表',
    'url': '/customer/list/'}]},
2: {'title': '订单管理', 'icon': 'fa-code-fork',
    'children': [{'title': '订单列表',
    'url': '/payment/list/'}]}}

    :param request:
    :return:
    """
    #菜单是无序的，要把顺序固定下来，将字典的key排序
    #默认的菜单要展开
    menu_dict = request.session.get(settings.MENU_SESSION_KEY)
    # print(request.current_selected_permission)
    #request.current_selected_permission的类型是数字
    #对字典的key进行排序
    key_list = sorted(menu_dict)
    #空的有序字典
    ordered_dict=OrderedDict()
    for key in key_list:
        val = menu_dict[key]
        val['class']='hide'
        for per in val['children']:
            #使用id比较后，就不需要url匹配了
            #regex = '^%s$' % per['url']
            if per['id'] == request.current_selected_permission:
                per['class']='active'
                val['class']=''
        ordered_dict[key]=val
    # print(ordered_dict)
    return {'menu_dict': ordered_dict}


@register.inclusion_tag('rbac/breadcrumb.html')
def breadcrumb(request):
    return {'breadcrumb':request.breadcrumb}

@register.filter
def has_permission(request,name):
    """
    判断是否有权限 request|has_permission："urlame"
    :param request:
    :param name:
    :return:
    """
    if name in request.session[settings.PERMISSION_SESSION_KEY]:
        return True
    else:
        return False

@register.simple_tag
def memory_url(request,name,*args,**kwargs):
    """"
    生成带有原搜索条件的URL,替换了原模板中的url
    """
    return urls.memory_url(request,name,*args,**kwargs)
